package com.hrp.book.ui.search

import android.app.Application
import androidx.databinding.ObservableField
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.hrp.analyzer.core.helper.RuleHelper
import com.hrp.analyzer.core.model.AnalyzerRule
import com.hrp.analyzer.model.Novel
import com.hrp.analyzer.spider.SearchSpider
import com.hrp.book.base.BaseViewModel
import com.hrp.book.utils.ConverterUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SearchModel(application: Application) : BaseViewModel(application) {

    companion object {
        const val DEFAULT_SOURCE = "百度"
    }

    val bookSource: ObservableField<String> by lazy {
        ObservableField(DEFAULT_SOURCE)
    }


    private var rulesList: List<AnalyzerRule> = emptyList()

    override fun initialize() {
        viewModelScope.launch(Dispatchers.IO) {
            val assetManager = context.assets
            val inputStream = assetManager.open("json/rules.json")
            val json = ConverterUtils.getString(inputStream)
            val size = RuleHelper.loadRules(json)
            LogUtils.e("test_", size)
            if (size > 0) {
                val list = RuleHelper.rules()
                if (!list.isNullOrEmpty()) {
                    rulesList = list
                    withContext(Dispatchers.Main) {
                        bookSource.set(list.first().name)
                    }
                }
            }
        }
    }


    suspend fun search(keyword: String): MutableList<Novel> {
        LogUtils.e("test_", keyword)
        if (keyword.isEmpty()) {
            return mutableListOf()
        }
        LogUtils.e("test_", rulesList.size)
        if (rulesList.isEmpty()) {
            return mutableListOf()
        }
        val rule = rulesList.last()
        return withContext(Dispatchers.IO) {
            val searchSpider = SearchSpider(listOf(rule))
            val novelList = mutableListOf<Novel>()
            searchSpider.setPageConsumer { pageNovels: List<Novel?> ->
                novelList.addAll(pageNovels.filterNotNull())
                LogUtils.e("test_books", novelList.size)

                novelList.forEach {
                    LogUtils.e("test_books", it.title)
                    LogUtils.e("test_books", it.chapters)
                }


            }
            searchSpider.search(keyword)
            searchSpider.loadMore()
            return@withContext novelList
        }
    }
}